<template>
  <div ref="boxwrap" class="user-wrap mt-50">
    <div class="table-main">
      <div class="table-list">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="Loading"
          :data="pageList"
          border
          fit
          style="width: 100%;"
          size="small"
          :height="tableHeight"
          :max-height="tableHeight"
          @current-change="handleSelection"
        >
          <el-table-column label="" align="center" width="60" fixed="left" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-radio v-model="currentChecked" :label="scope.row.checked"><span /></el-radio>
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" type="index" width="80" :index="indexMethod" />
          <el-table-column v-for="(item, index) in tableCol" :key="index" :label="item.label" align="center" :width="item.width || ''">
            <template slot-scope="scope">{{ scope.row[item.prop] }}</template>
          </el-table-column>
        </el-table>

        <pagination :total="pageObj.total" :page-sizes="pageObj.pageSize" :page.sync="pageObj.page" :limit.sync="pageObj.limit" layout="total, sizes, prev, pager, next" @pagination="getPage" />
      </div>

      <div class="operate-btns">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd()">新增</el-button>
        <el-button type="primary" plain icon="el-icon-edit" @click="handleUpdate()">编辑</el-button>
        <el-button slot="reference" type="primary" plain icon="el-icon-delete" @click="handleDelete()">删除</el-button>
      </div>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" class="dialog-form">
        <el-form-item
          label="用户名"
          :rules="[{ required: true, message: '必填项', trigger: 'blur' }]"
        >
          <el-input v-model.trim="temp.userName" placeholder="请输入" />
        </el-form-item>
        <el-form-item
          label="昵称"
          :rules="[{ required: true, message: '必填项', trigger: 'blur' }]"
        >
          <el-input v-model.trim="temp.nickName" placeholder="请输入" />
        </el-form-item>
        <el-form-item
          label="密码"
          :rules="[{ required: true, message: '必填项', trigger: 'blur' }]"
        >
          <el-input v-model.trim="temp.userPwd" type="password" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item label="角色">
          <el-select v-model="temp.roleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="small" @click="dialogStatus === 'update' ? updateData('dataForm') : addData('dataForm')">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getUserList, addUser, deleteUser, updateUser } from '@/api/user'
import { defaultRoles } from '@/api/default-apis'
import { getProcess } from '@/api/conf'
export default {
  name: 'Users',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: [],
      pageList: [],
      listLoading: false,
      roleList: [],
      tableCol: [
        { label: '建立日期', prop: 'createTime' },
        { label: '用户名', prop: 'userName' },
        { label: '昵称', prop: 'nickName' },
        { label: '角色', prop: 'roleName' },
        { label: '状态', prop: 'stateStr' },
        { label: '权限等级', prop: 'desc' },
        { label: '制程权限', prop: 'regionStr' }
      ],
      tableHeight: 'auto',
      temp: {
        userName: '',
        nickName: '',
        userPwd: ''
        // roleId: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      pageObj: {
        page: 1, // 第几页
        limit: 20, // 每页条数
        total: 0, // 总条数
        pageSize: [20, 40, 60, 80, 100]
      },
      currentChecked: '',
      currentSelectItem: null,
      userState: {
        0: '离职',
        1: '在职'
      },
      logedUser: {},
      regionNameObj: {}
    }
  },
  mounted() {
    this.getTableHeight()
  },
  created() {
    this.getAllRegion()
    this.logedUser = JSON.parse(this.$Cookies.get('logedUser'))
    // console.log('this.logedUser.roleId', this.logedUser)
  },
  methods: {
    getTableHeight() {
      const that = this
      const dom = this.$refs.boxwrap
      this.$erd.listenTo(dom, function(element) {
        that.tableHeight = dom.clientHeight - 50
      })
    },
    getAllRoles() {
      defaultRoles().then(res => {
        this.roleList = [].concat(res.roleList)
        this.handleSearch()
      })
    },
    getAllRegion() {
      getProcess().then(res => {
        res.data.forEach(item => {
          this.regionNameObj[item.id] = item.name
        })
        this.getAllRoles()
      })
    },
    handleSearch() {
      getUserList().then(res => {
        let role = {}
        res.data.forEach(item => {
          item.checked = item.userId
          role = this.roleList.filter(val => {
            return val.roleId === item.roleId
          })[0]
          item.roleName = role === undefined ? '' : role.roleName
          // item.auths = role.auths
          item.stateStr = this.userState[item.state]
          item.desc = role === undefined ? '' : role.desc
          if (item.regionId) {
            item.regionStr = item.regionId.split(',').map(val => { return this.regionNameObj[parseInt(val)] }).join(',')
          } else {
            item.regionStr = ''
          }
        })
        this.list = [].concat(res.data)
        this.pageObj.total = res.data.length
        this.getPage()
        this.listLoading = false
      })
    },
    getPage() {
      this.pageList = this.list.filter((item, index) => {
        return index < this.pageObj.limit * this.pageObj.page && index >= this.pageObj.limit * (this.pageObj.page - 1)
      })
    },
    indexMethod(index) { // 表格序号方法,翻页后序号连续
      return (index + 1) + (this.pageObj.page - 1) * this.pageObj.limit
      // return index + 1
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    // 选中行
    handleSelection(currentRow) {
      // console.log('currentRow', currentRow)
      if (currentRow) {
        this.currentChecked = currentRow.userId
        this.currentSelectItem = Object.assign({}, currentRow)
        this.currentSelectItem.checked = this.currentSelectItem.userId
      }
    },
    handleAdd() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    addData() {
      // console.log('新增', this.temp)
      addUser({
        userName: this.temp.userName,
        nickName: this.temp.nickName,
        userPwd: this.temp.userPwd
        // roleId: this.temp.roleId
      }).then(res => {
        let msgType = 'error'
        if (res.code === '000000') {
          this.handleSearch()
          this.dialogFormVisible = false
          this.resetForm()
          msgType = 'success'
        } else {
          this.$message({
            message: msgType,
            type: msgType,
            duration: 2000
          })
        }
      })
    },
    handleUpdate() {
      // console.log(this.currentSelectItem)
      if (this.currentSelectItem) {
        if (this.currentSelectItem.roleId === null || this.logedUser.roleId < this.currentSelectItem.roleId || (this.logedUser.roleId === this.currentSelectItem.roleId && this.logedUser.userName === this.currentSelectItem.userName)) {
          this.openDiaglog()
        } else {
          this.noAuthTip()
        }
      } else {
        this.$message({
          message: '请选择一条数据',
          type: 'warning'
        })
      }
    },
    openDiaglog() {
      this.temp = {
        userId: this.currentSelectItem.userId,
        userName: this.currentSelectItem.userName,
        nickName: this.currentSelectItem.nickName,
        userPwd: this.currentSelectItem.userPwd === '' ? null : this.currentSelectItem.userPwd,
        // roleId: this.currentSelectItem.roleId,
        state: this.currentSelectItem.state,
        checked: this.currentSelectItem.userId
      }
      // this.temp = Object.assign({}, this.currentSelectItem)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    noAuthTip() {
      this.$message({
        message: '权限不够，请联系上级管理员',
        type: 'warning'
      })
    },
    updateData(formname) {
      this.$refs[formname].validate((valid) => {
        const role = this.roleList.filter(val => {
          return val.roleId === this.temp.roleId
        })[0]
        this.temp.createTime = this.currentSelectItem.createTime
        this.temp.roleName = role.roleName
        this.temp.stateStr = this.userState[this.currentSelectItem.state]
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          console.log('updateData', tempData)
          updateUser(tempData).then(res => {
            let msgType = 'error'
            if (res.code === '000000') {
              msgType = 'success'
              // for (const v of this.list) {
              //   if (v.userId === tempData.userId) {
              //     const index = this.list.indexOf(v)
              //     this.list.splice(index, 1, this.tempData)
              //     // this.getPage()
              //     break
              //   }
              // }
              this.currentChecked = ''
              this.handleSearch()
            }
            this.$message({
              message: msgType,
              type: msgType,
              duration: 2000
            })
          }).then(() => {
            // console.log('list', this.list)
            this.dialogFormVisible = false
            // this.currentChecked = null
            // this.currentSelectItem.checked = null
            // this.currentSelectItem = {}
            this.resetForm()
          })
        }
      })
    },
    handleDelete() {
      if (this.currentSelectItem) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser({ userId: this.currentSelectItem.userId }).then(res => {
            if (res.code === '000000') {
              this.$notify({
                title: 'Success',
                message: 'Delete Successfully',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(this.currentSelectItem)
              this.list.splice(index, 1)
              // this.getPage()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$message({
          message: '请选择一条数据',
          type: 'warning'
        })
      }
    },
    cancel() {
      // this.currentChecked = ''
      this.dialogFormVisible = false
      // this.currentSelectItem = null
      this.resetForm()
    },
    resetForm() {
      this.temp = {
        userName: '',
        nickName: '',
        userPwd: ''
        // roleId: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .user-wrap{
    height: calc(100% - 50px);
  }
  .dialog-form{
    width: 50%;
    margin:0 auto;
  }
</style>
